package com.company.project.core.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * =================================
 * <p>
 * Created by cjj on 18-10-17.
 * <p>
 * 描述: 请求日志记录
 */

@Aspect
@Component
public class HttpLogAspect {

    private static final Logger log = LoggerFactory.getLogger(HttpLogAspect.class);

    /**
     * 定义切点 只定义在控制层，用来生成接口访问日志 以日志文件形式存储在磁盘中。
     **/
    @Pointcut("execution(* com.company.project.web..*Controller.*(..))")
    public void log() {
    }

    /**
     * 记录入参参数
     **/
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = attributes.getRequest();
        //记录请求url
        log.info("url={}", httpServletRequest.getRequestURL());

        //记录请求方式
        log.info("method={}", httpServletRequest.getMethod());

        //记录请求方法名的全路径
        log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //记录请求参数
        log.info("args={}", joinPoint.getArgs());
    }

    /**
     * 记录返回值
     **/
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        log.info("response={}", object.toString());
    }

}
